﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.WindowsAzure.StorageClient
Imports Microsoft.Samples.WindowsPhoneCloud.Web.UserAccountWrappers
Imports Microsoft.Samples.WindowsPhoneCloud.Web.Models
Imports Microsoft.Samples.WindowsPhoneCloud.Web.Controllers
Imports Microsoft.Samples.WindowsPhoneCloud.Web.Infrastructure
Imports Microsoft.Samples.ServiceHosting
Imports System.Globalization
Imports System.Collections.Generic

Namespace Controllers

    Public Class TablesController
        Inherits StorageItemController
        Private ReadOnly cloudTableClient As CloudTableClient

#If ACS Then
        Private ReadOnly userRepository As IUserRepository

        Public Sub New()
            Me.New(Nothing, New UserTablesServiceContext(), New UserTablesServiceContext())
        End Sub

        <CLSCompliant(False)> _
        Public Sub New(ByVal cloudTableClient As CloudTableClient, ByVal userPrivilegesRepository As IUserPrivilegesRepository, ByVal userRepository As IUserRepository)
            MyBase.New(userPrivilegesRepository)
            If (GetStorageAccountFromConfigurationSetting() Is Nothing) AndAlso (cloudTableClient Is Nothing) Then
                Throw New ArgumentNullException("cloudTableClient", "Cloud Table Client cannot be null if no configuration is loaded.")
            End If

            Me.cloudTableClient = If(cloudTableClient, GetStorageAccountFromConfigurationSetting().CreateCloudTableClient())
            Me.userRepository = userRepository
        End Sub

        Public Function Index() As ActionResult
            Dim permissions = New List(Of StorageItemPermissionsModel)()
            Dim tables = Me.cloudTableClient.ListTables()
            For Each tableName In tables
                If (Not tableName.Equals(Microsoft.Samples.ServiceHosting.AspProviders.AspProvidersConfiguration.DefaultMembershipTableName, StringComparison.OrdinalIgnoreCase)) AndAlso (Not tableName.Equals(UserTablesServiceContext.UserTableName, StringComparison.OrdinalIgnoreCase)) AndAlso (Not tableName.Equals(UserTablesServiceContext.UserPrivilegeTableName, StringComparison.OrdinalIgnoreCase)) AndAlso (Not tableName.Equals(UserTablesServiceContext.PushUserTableName, StringComparison.OrdinalIgnoreCase)) Then
                    Dim accessTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, PrivilegeConstants.TablePrivilegeSuffix)
                    Dim publicTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, PrivilegeConstants.PublicTablePrivilegeSuffix)
                    permissions.Add(New StorageItemPermissionsModel With {.StorageItemName = tableName, .IsPublic = Me.UserPrivilegesRepository.PublicPrivilegeExists(publicTablePrivilege), .AllowedUserIds = Me.UserPrivilegesRepository.GetUsersWithPrivilege(accessTablePrivilege).Select(Function(us) us.UserId)})
                End If
            Next tableName

            Me.ViewData("users") = Me.userRepository.GetAllUsers().Select(Function(user) New UserModel With {.UserName = user.Name, .UserId = user.UserId})

            Return Me.View(permissions)
        End Function
#Else
        Private ReadOnly membershipService As IMembershipService

        Public Sub New()
            Me.New(Nothing, New UserTablesServiceContext(), New AccountMembershipService())
        End Sub

        <CLSCompliant(False)> _
        Public Sub New(ByVal cloudTableClient As CloudTableClient, ByVal userPrivilegesRepository As IUserPrivilegesRepository, ByVal membershipService As IMembershipService)
            MyBase.New(userPrivilegesRepository)
            If (GetStorageAccountFromConfigurationSetting() Is Nothing) AndAlso (cloudTableClient Is Nothing) Then
                Throw New ArgumentNullException("cloudTableClient", "Cloud Table Client cannot be null if no configuration is loaded.")
            End If

            Me.cloudTableClient = If(cloudTableClient, GetStorageAccountFromConfigurationSetting().CreateCloudTableClient())
            Me.membershipService = membershipService
        End Sub

        Public Function Index() As ActionResult
            Dim permissions = New List(Of StorageItemPermissionsModel)()
            Dim tables = Me.cloudTableClient.ListTables()
            For Each tableName In tables
                If (Not tableName.Equals(ServiceHosting.AspProviders.AspProvidersConfiguration.DefaultMembershipTableName, StringComparison.OrdinalIgnoreCase)) AndAlso (Not tableName.Equals(UserTablesServiceContext.UserPrivilegeTableName, StringComparison.OrdinalIgnoreCase)) AndAlso (Not tableName.Equals(UserTablesServiceContext.PushUserTableName, StringComparison.OrdinalIgnoreCase)) Then
                    Dim accessTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, PrivilegeConstants.TablePrivilegeSuffix)
                    Dim publicTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", tableName, PrivilegeConstants.PublicTablePrivilegeSuffix)
                    permissions.Add(New StorageItemPermissionsModel With {.StorageItemName = tableName, .IsPublic = Me.UserPrivilegesRepository.PublicPrivilegeExists(publicTablePrivilege), .AllowedUserIds = Me.UserPrivilegesRepository.GetUsersWithPrivilege(accessTablePrivilege).Select(Function(us) us.UserId)})
                End If
            Next tableName

            Me.ViewData("users") = Me.membershipService.GetAllUsers().Cast(Of MembershipUser)().Select(Function(user) New UserModel With {.UserName = user.UserName, .UserId = user.ProviderUserKey.ToString()})

            Return Me.View(permissions)
        End Function
#End If

        <HttpPost()> _
        Public Sub AddTablePermission(ByVal table As String, ByVal userId As String)
            Dim accessTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", table, PrivilegeConstants.TablePrivilegeSuffix)
            Me.AddPrivilegeToUser(userId, accessTablePrivilege)
        End Sub

        <HttpPost()> _
        Public Sub RemoveTablePermission(ByVal table As String, ByVal userId As String)
            Dim accessTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", table, PrivilegeConstants.TablePrivilegeSuffix)
            Me.RemovePrivilegeFromUser(userId, accessTablePrivilege)
        End Sub

        <HttpPost()> _
        Public Sub SetTablePublic(ByVal table As String, ByVal isPublic As Boolean)
            Dim publicTablePrivilege = String.Format(CultureInfo.InvariantCulture, "{0}{1}", table, PrivilegeConstants.PublicTablePrivilegeSuffix)
            Me.SetPublicPrivilege(publicTablePrivilege, isPublic)
        End Sub
    End Class
End Namespace